package mo.tags.stack;

import java.util.Stack;

public class L331 {

    public boolean isValidSerialization(String preorder) {
        String[] nodes = preorder.split(",");
        int n = nodes.length;
        if (nodes[0].equals("#")) {
            return n == 1;
        }
        int i = 0;
        Stack<String> stack = new Stack<>();
        while (i < n) {
            if (nodes[i].equals("#")) {
                if (!stack.isEmpty() && stack.peek().equals("#")) {
                    stack.pop();
                    if (stack.isEmpty()) {
                        return false;
                    }
                    stack.pop();    //继续校验
                } else {
                    stack.push(nodes[i]);
                    i++;
                }
            } else {
                stack.push(nodes[i]);
                i++;
            }
        }
        return stack.size() == 1 && stack.peek().equals("#");
    }

    public static void main(String[] args) {
        L331 test = new L331();
        System.out.println(test.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"));
    }

}
